package com.grouppurchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grouppurchase.entity.User;
import com.grouppurchase.mapper.UserMapper;
import com.grouppurchase.service.UserService;
import com.grouppurchase.utils.RandomCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Override
    public User findByOpenid(String openid) {
        return userMapper.selectByOpenid(openid);
    }
    
    @Override
    @Transactional
    public User createOrUpdateUser(String openid, String unionid, String nickname, String avatar) {
        User user = findByOpenid(openid);
        
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setUnionid(unionid);
            user.setNickname(nickname);
            user.setAvatar(avatar);
            user.setRole(1);
            user.setTotalInvited(0);
            user.setTotalReward(0);
            user.setStatus(1);
            userMapper.insert(user);
            
            String inviteCode = generateInviteCode(user.getId());
            user.setInviteCode(inviteCode);
            userMapper.updateById(user);
        } else {
            if (nickname != null) user.setNickname(nickname);
            if (avatar != null) user.setAvatar(avatar);
            userMapper.updateById(user);
        }
        
        return user;
    }
    
    @Override
    public boolean updateUserInfo(Long userId, String nickname, String avatar, String phone) {
        User user = getById(userId);
        if (user == null) {
            return false;
        }
        
        if (nickname != null) user.setNickname(nickname);
        if (avatar != null) user.setAvatar(avatar);
        if (phone != null) user.setPhone(phone);
        
        return updateById(user);
    }
    
    @Override
    public String generateInviteCode(Long userId) {
        return RandomCodeGenerator.generateInviteCode(userId);
    }
    
    @Override
    @Transactional
    public boolean handleUserInvite(Long inviteeId, String inviteCode) {
        if (inviteCode == null || inviteCode.isEmpty()) {
            return true;
        }
        
        User inviter = findByInviteCode(inviteCode);
        if (inviter == null || inviter.getId().equals(inviteeId)) {
            return false;
        }
        
        return userMapper.updateInviteInfo(inviteeId, inviter.getId()) > 0;
    }
    
    @Override
    public User findByInviteCode(String inviteCode) {
        return userMapper.selectByInviteCode(inviteCode);
    }
}
